<template>
  <div class="wrapper">
    <div class="upload-card-item">
      <n-spin :show="isUploading" description="上传中">
        <div class="upload-card-item-info">
          <video v-if="isVideo" class="upload-video" :src="thumbnailUrl || element" muted />
          <img v-else class="upload-img" :src="thumbnailUrl || formatCdn(element)" />
          <div v-if="!isUploading" class="img-box-actions">
            <n-icon size="18" class="action-icon" @click="handlePreview">
              <n-tooltip>
                <template #trigger>
                  <EyeOutlined />
                </template>
                预览
              </n-tooltip>
            </n-icon>
            <n-icon v-if="!disabled" size="18" class="action-icon" @click="handleRemove">
              <n-tooltip>
                <template #trigger>
                  <DeleteOutlined />
                </template>
                删除
              </n-tooltip>
            </n-icon>
          </div>
        </div>
      </n-spin>
    </div>

    <!--预览图片-->
    <n-modal v-model:show="showModal" preset="card" title="预览" :bordered="false" :style="{ width: '520px' }">
      <div class="flex center">
        <video v-if="isVideo" style="width: 100%; max-height: 500px" :src="thumbnailUrl || element" controls muted />
        <n-image v-else class="preview-img" :src="thumbnailUrl || element" />
      </div>
      <n-button v-if="props.showDownload" text @click="downloadImage">下载</n-button>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
  import { DeleteOutlined, EyeOutlined } from '@vicons/antd'
  import { NIcon, NImage, NModal, NTooltip, NSpin, NButton } from 'naive-ui'
  import { computed, ref } from 'vue'
  import { formatCdn } from '@/utils'

  const emits = defineEmits(['delete'])
  const props = defineProps({
    disabled: {
      type: Boolean,
      default: false
    },
    element: {
      type: [String, Object],
      default: ''
    },
    isVideo: {
      type: Boolean,
      default: false
    },
    index: {
      type: Number,
      default: 0
    },
    showDownload: {
      type: Boolean,
      default: false
    }
  })
  const showModal = ref(false)
  const isUploading = computed(() => {
    return !!(props.element?.id && props.element?.percentage < 100)
  })
  const thumbnailUrl = computed(() => {
    let url = ''
    if (props.element?.id) {
      url = URL.createObjectURL(props.element.file)
    }
    return url
  })
  const downloadImage = async () => {
    try {
      const img = thumbnailUrl.value || props.element
      const response = await fetch(img)
      if (!response.ok) {
        throw new Error('Network response was not ok')
      }
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'sample-image.jpg' // 你希望下载的文件名
      link.style.display = 'none' // 隐藏元素
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Download failed:', error)
    }
  }
  function handleRemove() {
    emits('delete', props.index, props.element)
  }

  function handlePreview() {
    showModal.value = true
  }
</script>

<style scoped lang="scss">
  .wrapper {
    margin: 0 8px 8px 0;
    .upload-card-item {
      width: 100%;
      height: 100%;
      position: relative;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      overflow: hidden;

      &-info {
        position: relative;
        width: 100%;
        height: 100%;
        padding: 0;
        overflow: hidden;
        display: flex;

        &:before {
          position: absolute;
          z-index: 1;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.5);
          opacity: 0;
          transition: all 0.3s;
          content: ' ';
        }

        &:hover {
          &:before {
            opacity: 1;
          }

          .img-box-actions {
            opacity: 1;
          }
        }

        .upload-img {
          width: 100%;
          height: 100%;
          margin: auto;
          object-fit: contain;
        }

        .upload-video {
          width: 100%;
          max-height: 100%;
          margin: auto;
        }

        .img-box-actions {
          position: absolute;
          top: 50%;
          left: 50%;
          z-index: 10;
          white-space: nowrap;
          transform: translate(-50%, -50%);
          opacity: 0;
          transition: all 0.3s;
          display: flex;
          align-items: center;
          justify-content: space-between;

          .action-icon {
            margin: 0 5px;
            color: rgba(255, 255, 255, 0.85);

            &:hover {
              cursor: pointer;
              color: #fff;
            }
          }
        }
      }
    }
  }
</style>
